package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.utils.DateUtils;
import com.sangmo.boot.framework.data.idm.IdentityManager;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.inventory.interfaces.IfWaybillCreation;
import com.sangmo.fts.process.inventory.interfaces.IfWaybillItemCreation;
import com.sangmo.fts.process.inventory.model.IfContract;
import com.sangmo.fts.process.inventory.model.IfWaybill;
import com.sangmo.fts.process.inventory.model.IfWaybillItem;
import com.sangmo.fts.process.inventory.repo.IfWaybillRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class IfWaybillEntityService extends AuthorityEntityService<IfWaybill> {

    @Autowired
    private IfWaybillRepo ifWaybillRepo;

    @Autowired
    private IdentityManager identityManager;

    @Autowired
    private IfContractService ifContractService;

    @Autowired
    private IfWaybillItemEntityService ifWaybillItemEntityService;

    @Override
    protected IDataViewRepo<IfWaybill> getRepo() {
        return ifWaybillRepo;
    }


    @Override
    protected void onCreate(IfWaybill entity, Object bo) {
        super.onCreate(entity, bo);
        entity.setCode(DateUtils.format(new Date(), "yyyyMMddHHmmss") + identityManager.next("IF_WAYBILL", 4));
        IfContract contract = ifContractService.get(entity.getContractId());
        entity.setShipper(contract.getPledgor());
        entity.setConsignee(contract.getRegulator());
    }

    @Override
    protected void afterCreated(IfWaybill entity, Object bo) {
        super.afterCreated(entity, bo);
        IfWaybillCreation creation = (IfWaybillCreation) bo;
        List<IfWaybillItem> waybillItems = buildIfWaybillItems(entity.getId(), creation.getWaybillItems());
        ifWaybillItemEntityService.saveAll(waybillItems);
    }

    private List<IfWaybillItem> buildIfWaybillItems(Long waybillId, List<IfWaybillItemCreation> waybillItemCreations) {
        List<IfWaybillItem> waybillItems = new ArrayList<>();
        for (IfWaybillItemCreation waybillItem : waybillItemCreations) {
            IfWaybillItem item = new IfWaybillItem();
            item.setGoodsId(waybillItem.getGoodsId());
            item.setQuantity(waybillItem.getQuantity());
            item.setWaybillId(waybillId);
            waybillItems.add(item);
        }
        return waybillItems;
    }
}
